package com.tuanzi.loan.schedule.receipt;

import com.tuanzi.loan.business.entity.family.LoanWholeSaleComment;
import com.tuanzi.loan.business.service.family.LoanWholeSaleCommentService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.server.loan_base.constant.LoanRedisKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * User: liangZongXi
 * Create time: 14:30 2019/7/30
 * Description: 大额产品到量自动下线调度器
 */
@Debug
@Slf4j
@Service
public class LargeProductAutoDownScheduler {

    @Autowired
    private LoanWholeSaleCommentService loanWholeSaleCommentService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Scheduled(cron = "${cron.large-product-limit}")
    @Transactional(propagation= Propagation.NOT_SUPPORTED)
    public void process(){
        log.info("大额产品限量调度器执行开始...");
        List<LoanWholeSaleComment> allOnLineProducts = loanWholeSaleCommentService.findAllByStatus(1);
        for (LoanWholeSaleComment saleComment : allOnLineProducts) {
            Integer totalLimit = saleComment.getTotalLimit();
            if(null != totalLimit){
                String limitKey = LoanRedisKey.largeTotalNumKey(saleComment.getType());
                String currentCountStr = stringRedisTemplate.boundValueOps(limitKey).get();
                int currentCount = NumberUtils.toInt(currentCountStr);
                if(currentCount >= totalLimit){
                    saleComment.setStatus(0);
                    saleComment.setUpdator("系统操作");
                    Integer count = loanWholeSaleCommentService.updateLoanWholeSaleComment(saleComment);
                    if(1== count){
                        stringRedisTemplate.delete(limitKey); //清除总量
                    }
                }
            }
        }
        log.info("大额产品限量调度器执行完毕...");
    }


}
